//
//  TYZCustomTabBarController.m
//  TYZKit
//
//  Created by TangBin on 2018/8/23.
//  Copyright © 2018年 TangBin. All rights reserved.
//

#import "TYZCustomTabBarController.h"
#import "TYZBaseNavigationController.h"
#import "TYZNavRootVCInfo.h"

@interface TYZCustomTabBarController ()
{
    BOOL _isShowMiddleBulgeBtn;
}

@property (nonatomic, copy) NSString *midNorImgName;
@property (nonatomic, copy) NSString *midSelImgName;

@end

/*
 @throw [NSException exceptionWithName:@"TYZKVStorage init error" reason:@"Please use the designated initializer and pass the 'path' and 'type'." userInfo:nil];
 return [self initWithPath:@"" type:TYZKVStorageTypeFile];
 */

@implementation TYZCustomTabBarController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    @throw [NSException exceptionWithName:@"initWithNibName error" reason:@"Please use the designated initializer 'initWithShowMiddleBtn'" userInfo:nil];
//    return [self initWithShowMiddleBtn:NO midNorImgName:nil midSelImgName:nil];
//}
//
//- (instancetype)init
//{
//    @throw [NSException exceptionWithName:@"init error" reason:@"Please use the designated initializer 'initWithShowMiddleBtn'" userInfo:nil];
//    return [self initWithShowMiddleBtn:NO midNorImgName:nil midSelImgName:nil];
//}

- (instancetype)initWithShowMiddleBtn:(BOOL)showMiddleBtn midNorImgName:(NSString *)midNorImgName midSelImgName:(NSString *)midSelImgName
{
    _isShowMiddleBulgeBtn = showMiddleBtn;
    self.midNorImgName = midNorImgName;
    self.midSelImgName = midSelImgName;
    if (self = [super init])
    {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
//    self.delegate = self;
    
    // 设置TabBarItemtestAttributes的颜色
//    [self setupTabBarItemTextAttributes];
    
    // 设置子控制器
//    [self setupChildViewController];
    
    // 处理tabBar，使用自定义tabBar添加发布按钮
    [self setupTabBar];
    
    if (@available(iOS 15.0, *))
    {
        UITabBarAppearance *tabApp = [[UITabBarAppearance alloc] init];
        tabApp.backgroundColor = kTabBarBackgroundColor;
        tabApp.shadowImage = [self imageWithColor:kTabBarBackgroundColor];//[[UIImage alloc] init];
        
        NSDictionary *dict = @{NSForegroundColorAttributeName:kTabBarItemTitleSelColor, NSFontAttributeName:kTabBarItemTitleFont};
        tabApp.stackedLayoutAppearance.selected.titleTextAttributes = dict; // 设置选中的attributes
        dict = @{NSForegroundColorAttributeName:kTabBarItemTitleNorColor, NSFontAttributeName:kTabBarItemTitleFont};
        tabApp.stackedLayoutAppearance.normal.titleTextAttributes = dict;
        
        self.tabBar.scrollEdgeAppearance = tabApp;
        self.tabBar.standardAppearance = tabApp;
    }
    else
    {
        [[UITabBar appearance] setBackgroundImage:[self imageWithColor:kTabBarBackgroundColor]];
        
        // 去除TabBar自带的顶部阴影
        [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    }
//    TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:[UIColor colorWithHexString:@"#3688ff"] titleFont:[UIFont boldSystemFontOfSize:18] titleColor:[UIColor whiteColor]];
//    [self setupNavCommonInfo:navInfo];
    
    self.appTabBarHeight = self.tabBar.height;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - private methods
/**
 *  利用KVC把系统的tabBar类型改为自定义的类型
 */
- (void)setupTabBar
{
//    TYZTabBar *tabBar = [[TYZTabBar alloc] initWithShowMiddleBtn:_isShowMiddleBulgeBtn midNorImgName:_midNorImgName midSelImgName:_midSelImgName];
//    [self setValue:tabBar forKey:@"tabBar"];
}

/**
 *  添加一个子控制器
 *
 *  @param viewController    控制器
 *  @param title             标题
 *  @param imageName         图片
 *  @param selectedImageName 选中图片
 */
- (void)addChildViewController:(UIViewController *)viewController withTitle:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName
{
    viewController.tabBarItem.title = title;
//    UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
//    viewController.tabBarItem.imageInsets = UIEdgeInsetsMake(0, 0, 3.5, 0);//UIEdgeInsetsMake(-3.5, 0, 3.5, 0);
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.image = image;
    image = [UIImage imageNamed:selectedImageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.selectedImage = image;
    [self addChildViewController:viewController];
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    NSParameterAssert(color != nil);
    
    CGRect rect = CGRectMake(0, 0, 1, 1);
    // Create a 1 by 1 pixel context
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    [color setFill];
    UIRectFill(rect);   // Fill it with your color
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}

#pragma mark - public methods

- (void)setupNavCommonInfo:(TYZNavInfo *)navInfo
{
    /*
    UINavigationBar *navigationBar = [UINavigationBar appearance];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        [navigationBar setBarTintColor:navInfo.bgColor];
    }
    else
    {
        [navigationBar setTintColor:navInfo.bgColor];
    }
    
    navInfo.titleColor = [UIColor magentaColor];
    
    // navBar title Color font
    [navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:navInfo.titleColor, NSFontAttributeName:navInfo.titleFont}];
    
    // 去除自带的顶部阴影
    navigationBar.shadowImage = [[UIImage alloc] init];
    
    // 设置导航栏控制器颜色
    [navigationBar setBackgroundImage:[UIImage imageWithColor:navInfo.bgColor] forBarMetrics:UIBarMetricsDefault];
    
    if ([navigationBar respondsToSelector:@selector(setTranslucent:)])
    {
        // 设置导航栏是否具有透明度这个功能
        navigationBar.translucent = NO;
    }
     */
}

- (void)setupTabBarItemTextAttributes:(UIColor *)norTitleColor selTitleColor:(UIColor *)selTitleColor titleFont:(UIFont *)titleFont
{
    // 普通状态下的文字属性
    NSDictionary *normalAttrs = @{NSForegroundColorAttributeName:norTitleColor, NSFontAttributeName:titleFont};
    
    // 选中状态下的文字属性
    NSDictionary *selectedAttrs = @{NSForegroundColorAttributeName:selTitleColor, NSFontAttributeName:titleFont};
    
    // 设置文字属性
    UITabBarItem *tabBarItem = [UITabBarItem appearance];
    [tabBarItem setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBarItem setTitleTextAttributes:selectedAttrs forState:UIControlStateHighlighted];
    [tabBarItem setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // 设置标题的位置
//    tabBarItem.titlePositionAdjustment = UIOffsetMake(0.0, -3.0);
}

- (void)setupChildViewController:(NSArray<TYZNavRootVCInfo *> *)subControllers navInfo:(TYZNavInfo *)navInfo
{
    for (TYZNavRootVCInfo *vcInfo in subControllers)
    {
        UIViewController *vc = nil;
        Class cls = nil;
        if (vcInfo.vc)
        {
            vc = vcInfo.vc;
        }
        else
        {
            cls = NSClassFromString(vcInfo.className);
        }
        if (vcInfo.initSel == nil)
        {
            if (vc == nil)
            {
                vc = [[cls alloc] init];
            }
        }
        else
        {
            if (vc == nil)
            {
                vc = [cls alloc];
                NSMethodSignature *sig  = [[vc class] instanceMethodSignatureForSelector:vcInfo.initSel];
                NSInvocation *invocatin = [NSInvocation invocationWithMethodSignature:sig];
                [invocatin setTarget:vc];
                [invocatin setSelector:vcInfo.initSel];
                
                int i = 2;
                for (id param in vcInfo.methodParams)
                {
                    [invocatin setArgument:(void *)&param atIndex:i];
                    i += 1;
                }
                [invocatin invoke];
            }
            
        }
        vc.title = vcInfo.title;
        TYZBaseNavigationController *nav = [[TYZBaseNavigationController alloc] initWithRootViewController:vc];
        [nav setupNavCommonInfo:navInfo];
        [self addChildViewController:nav withTitle:vcInfo.title imageName:vcInfo.imgNorName selectedImageName:vcInfo.imgSelName];
    }
}

/*
// 是否支持旋转
- (BOOL)shouldAutorotate
{
    return [self.selectedViewController shouldAutorotate];
}

// 返回nav栈中的最后一个对象支持的旋转方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return [self.selectedViewController supportedInterfaceOrientations];
}

// 返回nav栈中最后一个对象，坚持旋转的方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}*/

- (BOOL)prefersStatusBarHidden
{
    if (self.selectedViewController.prefersStatusBarHidden)
    {
        return self.selectedViewController.prefersStatusBarHidden;
    }
    return NO;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    if (self.selectedViewController.preferredStatusBarUpdateAnimation)
    {
        return self.selectedViewController.preferredStatusBarUpdateAnimation;
    }
    return UIStatusBarAnimationNone;
}

// 是否支持旋转
- (BOOL)shouldAutorotate
{
    if (self.selectedViewController.shouldAutorotate)
    {
        return [self.selectedViewController shouldAutorotate];
    }
    return YES;
}

// 返回nav栈中的最后一个对象支持的旋转方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if (self.selectedViewController.supportedInterfaceOrientations)
    {
        return [self.selectedViewController supportedInterfaceOrientations];
    }
    return UIInterfaceOrientationPortrait;
}

// 返回nav栈中最后一个对象，坚持旋转的方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    if (self.selectedViewController.preferredInterfaceOrientationForPresentation)
    {
        return self.selectedViewController.preferredInterfaceOrientationForPresentation;
    }
    return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}

@end






















